package com.jiumi.api.controller;

import cn.hutool.core.date.DateUtil;
import com.jiumi.api.base.BaseApiController;
import com.jiumi.api.entity.SysUserDo;
import com.jiumi.api.service.ILoginApiService;
import com.jiumi.api.util.WeiXinUtil;
import com.jiumi.api.vo.WxLoginVo;
import com.jiumi.baseconfig.domain.*;
import com.jiumi.baseconfig.service.*;
import com.jiumi.common.constant.Constants;
import com.jiumi.common.constant.UserConstants;
import com.jiumi.common.core.domain.AjaxResult;
import com.jiumi.common.core.domain.entity.SysUser;
import com.jiumi.common.core.domain.model.LoginBody;
import com.jiumi.common.core.redis.RedisCache;
import com.jiumi.common.utils.DateUtils;
import com.jiumi.common.utils.SecurityUtils;
import com.jiumi.common.utils.StringUtils;
import com.jiumi.config.WeiXinConfig;
import com.jiumi.framework.web.service.SysLoginService;
import com.jiumi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author lun.zhang
 * @create 2022/10/18 10:58
 */
@RestController
@RequestMapping("/api")
public class LoginApiController extends BaseApiController {
    @Autowired
    private WeiXinConfig weiXinConfig;
    @Autowired
    private ILoginApiService loginApiService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IBaseUserService userInfoService;

    @Autowired
    private IBaseCompanyService baseCompanyService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IBaseScoreConfigService baseScoreConfigService;

    @Autowired
    private IScoreHistoryService scoreHistoryService;

    @Autowired
    private IRegisterHistoryService registerHistoryService;


    @PostMapping("/noAuth/login")
    public AjaxResult login(@Validated @RequestBody WxLoginVo wxLoginVo) {
        String appId = weiXinConfig.getAppId();
        String appSecret = weiXinConfig.getAppSecret();
        Map<String, Object> mapResult = new HashMap<>();
        if ("debug".equalsIgnoreCase(wxLoginVo.getCode())) {
            mapResult.put("openid", wxLoginVo.getCode());
        } else {
            mapResult = WeiXinUtil.getWxUserOpenId(wxLoginVo.getCode(), appId, appSecret);
        }
        Object openid = mapResult.get("openid");
        String unionid = null;
        if (StringUtils.isNotNull(mapResult.get("unionid"))) {
            unionid = (String) mapResult.get("unionid");
        }
        if (StringUtils.isNull(openid)) {
            return AjaxResult.error("获取openid失败!");
        }
        mapResult.put("avatar", wxLoginVo.getAvatarUrl());
        mapResult.put("sex", wxLoginVo.getGender());
        mapResult.put("nickName", wxLoginVo.getNickName());
        mapResult.put("unionid", unionid);
        Map<String, Object> login = loginApiService.login(mapResult);
        return AjaxResult.success(login);
    }

    @PostMapping("/loginApp1")
    public AjaxResult loginApp1(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginApiService.loginApp(loginBody.getUsername(), loginBody.getPassword(), loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @PostMapping("/loginApp2")
    public AjaxResult loginApp2(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();

        // 生成令牌
        String token = loginApiService.loginByCode(loginBody.getUsername(), loginBody.getCode(), loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 用户注册接口
     */
    @PostMapping("/noAuth/userRegister")
    public AjaxResult userRegister(@Validated @RequestBody SysUserDo user) {

        //演示环境注释掉了这段代码，正式环境需要放开
        /*String key = "phone_verify_code" + user.getUserName();
        String code = redisCache.getCacheObject(key) + "";
        if (!user.getCode().equals(code)) {
            return AjaxResult.error("验证码错误");
        }*/

        if (StringUtils.isEmpty(user.getAgainPassword())) {
            return AjaxResult.error("确认密码不能为空");
        }
        if (!user.getAgainPassword().equals(user.getPassword())) {
            return AjaxResult.error("密码与确认密码不一致");
        }
        BaseUser baseUser = userInfoService.selectUserByUserName(user.getUserName());

        BaseUser referrerUser = userInfoService.selectUserByReferrerCode(user.getInviteCode());
        BaseCompany company = null;
        if (referrerUser != null) {
            if("03".equals(referrerUser.getUserType()) || "04".equals(referrerUser.getUserType())){
                String companyId = configService.selectConfigByKey("sys.account.companyId");
                if (StringUtils.isEmpty(companyId)) {
                    companyId = "1";
                }
                company = baseCompanyService.selectBaseCompanyById(Long.valueOf(companyId));
            }else {
                company = baseCompanyService.selectBaseCompanyById(referrerUser.getCompanyId());
            }

        }
        if (company == null) {
            String companyId = configService.selectConfigByKey("sys.account.companyId");
            if (StringUtils.isEmpty(companyId)) {
                companyId = "1";
            }
            company = baseCompanyService.selectBaseCompanyById(Long.valueOf(companyId));
        }
        BaseScoreConfig regReward = baseScoreConfigService.selectBaseScoreConfigById(1L);
        BaseUser regUser = new BaseUser();
        regUser.setUserName(user.getUserName());
        regUser.setNickName("");
        regUser.setUserType(user.getUserType());
        regUser.setPhonenumber(user.getUserName());
        regUser.setCreateBy(user.getUserName());
        regUser.setCreateTime(DateUtils.getNowDate());
        regUser.setScoreAmount(regReward.getRewardAmount());
        String str = String.valueOf(ThreadLocalRandom.current().ints(100000, 999999).limit(1).findFirst().getAsInt());
        regUser.setReferrerCode(str);
        regUser.setInviteCode(user.getInviteCode());
        regUser.setPassword(SecurityUtils.encryptPassword(user.getPassword()));

        if ("03".equals(user.getUserType()) || "04".equals(user.getUserType())) {
            regUser.setCompanyId(company.getId());
            regUser.setCompanyName(company.getCompanyName());
            regUser.setAuthUserId(company.getUserId());
            if ("04".equals(user.getUserType())) {
                regUser.setStatus("02");
                regUser.setClickStatus("01");
                regUser.setClickTime(DateUtils.getNowDate());
            }
        }
        if (referrerUser != null && ("01".equals(referrerUser.getUserType()) || "02".equals(referrerUser.getUserType()) || "05".equals(referrerUser.getUserType())))
        {
            regUser.setAuthUserId(referrerUser.getUserId());
        }
        regUser.setPublishType("01");
        if (baseUser != null) {
            if("02".equals(baseUser.getPublishType()) && "04".equals(baseUser.getUserType())){
                regUser.setUserId(baseUser.getUserId());
                regUser.setCompanyId(null);
                regUser.setCompanyName(null);
                regUser.setInviteCode(null);
                regUser.setAuthUserId(null);
                userInfoService.updateBaseUser(regUser);
                return AjaxResult.success();
            }else {
                return AjaxResult.error("用户已存在，请登录");
            }
        }
        int r = userInfoService.insertBaseUser(regUser);
        if (r > 0) {
            RegisterHistory hisparam=new RegisterHistory();
            hisparam.setUserPhone(regUser.getPhonenumber());
            List<RegisterHistory> regHisList= registerHistoryService.selectRegisterHistoryList(hisparam);
            if(regHisList.size()>0) {
                ScoreHistory his = new ScoreHistory();
                his.setUserId(regUser.getUserId());
                his.setUserName(regUser.getUserName());
                his.setRemark("注册赠送积分");
                his.setScore(new BigDecimal(regReward.getRewardAmount()));
                his.setCreateTime(DateUtils.getNowDate());
                scoreHistoryService.insertScoreHistory(his);
                //推荐人添加邀请积分
                if (referrerUser != null) {
                    BaseScoreConfig refReward = baseScoreConfigService.selectBaseScoreConfigById(2L);
                    referrerUser.setScoreAmount(referrerUser.getScoreAmount() + refReward.getRewardAmount());
                    userInfoService.updateBaseUserScore(referrerUser);

                    ScoreHistory refHis = new ScoreHistory();
                    refHis.setUserId(referrerUser.getUserId());
                    refHis.setUserName(referrerUser.getUserName());
                    refHis.setRemark("邀请注册赠送积分");
                    refHis.setScore(new BigDecimal(refReward.getRewardAmount()));
                    refHis.setCreateTime(DateUtils.getNowDate());
                    scoreHistoryService.insertScoreHistory(refHis);
                }
            }
        }
        RegisterHistory regHis=new RegisterHistory();
        regHis.setUserName(regUser.getUserName());
        regHis.setUserPhone(regUser.getPhonenumber());
        regHis.setRegisterTime(DateUtils.getNowDate());
        regHis.setCreateTime(DateUtils.getNowDate());
        regHis.setCreateBy(regUser.getUserName());
        registerHistoryService.insertRegisterHistory(regHis);
        return AjaxResult.success();
    }


    @PutMapping("/noAuth/fogetPwd")
    public AjaxResult fogetPwd(@RequestBody SysUserDo user) {

        //演示环境注释掉了这段代码，正式环境需要放开
       /* String key = "phone_verify_code" + user.getUserName();
        String code = redisCache.getCacheObject(key) + "";
        if (!user.getCode().equals(code)) {
            return AjaxResult.error("验证码错误");
        }*/

        if (StringUtils.isEmpty(user.getAgainPassword())) {
            return AjaxResult.error("确认密码不能为空");
        }
       /* BaseUser currentUser = userInfoService.selectUserByUserPhone(user.getUserName());
        String password = SecurityUtils.encryptPassword(user.getPassword());*/
        String againPwd = SecurityUtils.encryptPassword(user.getAgainPassword());
        if (!user.getPassword().equals(user.getAgainPassword())) {
            return AjaxResult.error("两次密码不一致");
        }

        return toAjax(userInfoService.resetUserPwdByPhone(user.getUserName(), againPwd));
    }

    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUserDo user) {
        if (StringUtils.isEmpty(user.getAgainPassword())) {
            return AjaxResult.error("确认密码不能为空");
        }
        BaseUser currentUser = userInfoService.selectBaseUserByUserId(getUserId());
        String againPwd = SecurityUtils.encryptPassword(user.getAgainPassword());
        String password = configService.selectConfigByKey("sys.user.initPassword");
        if (!SecurityUtils.matchesPassword(user.getPassword(), currentUser.getPassword())) {
            return AjaxResult.error("当前密码错误，如果从未设置过密码可以尝试：" + password);
        }

        return toAjax(userInfoService.resetUserPwdByPhone(currentUser.getUserName(), againPwd));
    }


}
